package cn.com.shuyangyang.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.shuyangyang.common.Context;
import cn.com.shuyangyang.common.RequestContext;
import cn.com.shuyangyang.controller.response.ApplicationErrorResponse;
import cn.com.shuyangyang.controller.response.EmptyResponse;
import cn.com.shuyangyang.controller.response.ExceptionResponse;
import cn.com.shuyangyang.controller.response.NormalResponse;
import cn.com.shuyangyang.controller.response.Response;
import cn.com.shuyangyang.domain.EnumStatus;
import cn.com.shuyangyang.domain.LoginLog;
import cn.com.shuyangyang.domain.Menu;
import cn.com.shuyangyang.domain.MenuPermission;
import cn.com.shuyangyang.domain.MenuTree;
import cn.com.shuyangyang.domain.Permission;
import cn.com.shuyangyang.domain.RoleMenu;
import cn.com.shuyangyang.domain.User;
import cn.com.shuyangyang.service.MenuPermissionService;
import cn.com.shuyangyang.service.MenuService;
import cn.com.shuyangyang.service.PermissionService;
import cn.com.shuyangyang.service.RoleMenuService;
import cn.com.shuyangyang.service.UserService;


@Controller
@RequestMapping("/menu/")
public class MenuController {
	
	Logger	logger	= LoggerFactory.getLogger(MenuController.class);
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private RoleMenuService roleMenuService;
	
	@Autowired
	private MenuPermissionService menuPermissionService;
	
	@Autowired
	private PermissionService permissionService;
	
	@Autowired
	private UserService userService;

	/**
	 * 根据用户分配的关系显示菜单
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("showMenu")
	@ResponseBody
	public Response Menus(HttpServletRequest req, HttpServletResponse resp) {
		try{
			HttpSession session = req.getSession();
			LoginLog loginLog = (LoginLog) session.getAttribute("loginLogInfo");
			String loginName = loginLog.getLoginName();
			User user = userService.getUserByLoginName(loginName);
			List<Menu> menus = menuService.findMenuByPermiParams(user.getUser_id());
			List<Menu> menusNew = new ArrayList<Menu>();
			List<Menu> menus2 = new ArrayList<Menu>();
			List<Menu> menus3 = null;
			for(Menu menuNode:menus){
				if(menuNode.getFatherId().equals("-1")){
					menusNew.add(menuNode);
				}
			}
			
			for(Menu menuNode:menusNew){
				for(Menu menu:menus){
					if(menu.getFatherId().equals(menuNode.getMenu_id())){
						menus2.add(menu);
					}
				}
			}
			
			for(Menu menuNode:menusNew){
				menus3 = new ArrayList<Menu>();
				for(Menu menu:menus2){
					if(menuNode.getMenu_id().equals(menu.getFatherId())){
						menus3.add(menu);
					}
				}
				menuNode.setChildren(menus3);
			}
			return new NormalResponse(menusNew);
		}catch(Exception e){
			logger.error("读取菜单环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("showMenuByConf")
	@ResponseBody
	public List<Menu> MenusConfig(HttpServletRequest req, HttpServletResponse resp) {
		List<Menu> menus = menuService.FindMenus();
		return menus;
	}
	
	@RequestMapping("showMenuTree")
	@ResponseBody
	public List<MenuTree> MenusTree(HttpServletRequest req, HttpServletResponse resp) {
		String roleId = req.getParameter("roleId");
		List<RoleMenu> roleMenus = roleMenuService.getRoleMenuByUserId(roleId);
		List<MenuTree> menuTrees = menuService.FindMenusTree();
		for (RoleMenu roleMenu : roleMenus) {
			for (MenuTree menuTree : menuTrees) {
				String menId = menuTree.getMenu_id();
				String roleMenuId = roleMenu.getMenu_id();
				for(MenuTree menuTreeNode:menuTree.getChildren()){
					if (roleMenuId.equals(menuTreeNode.getMenu_id())) {
						menuTreeNode.setChecked(true);
					}
				}
				if (roleMenuId.equals(menId)) {
					menuTree.setChecked(true);
				}
			}
		}
		return menuTrees;
	}
	
	@RequestMapping("loadMenu")
	@ResponseBody
	public Response loadMenu(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		try {
			Context context = new RequestContext(request);
			Menu menu = menuService.findMenuByMenuId(context);
			if(menu!=null){
				return new NormalResponse(menu);
			}else{
				return new EmptyResponse("菜单数据");
			}
		} catch (Exception e) {
			logger.error("读取菜单环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("updateMenu")
	@ResponseBody
	public Response updateMenu(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		try {
			Context context = new RequestContext(request);
			menuService.updateMenuByMenuId(context);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("更新菜单环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("saveMenu")
	@ResponseBody
	public Response saveMenu(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		try {
			Context context = new RequestContext(request);
			boolean flag = menuService.addMenu(context);
			if(flag){
				return new NormalResponse();
			}else{
				return new ApplicationErrorResponse("添加失败，已存在的菜单名称");
			}
		} catch (Exception e) {
			logger.error("添加节点环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("deleteMenu")
	@ResponseBody
	public Response deleteMenu(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		try {
			Context context = new RequestContext(request);
			menuService.deleteMenuByMenuId(context);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("添加节点环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("showAllMenu")
	@ResponseBody
	public Response showAllMenu(HttpServletRequest request, HttpServletResponse response){
//		String start = request.getParameter("start");//起始页
//        String limit = request.getParameter("limit");//每页数量
//        int index = Integer.parseInt(start);
//        int pageSize = Integer.parseInt(limit);
        List<Menu> menus = menuService.FindMenusAll();
        long total = menus.size();
        if(total>0){
			logger.debug("now {}" , "返回菜单数据。。。");
			return new NormalResponse(menus);
		}else{
			logger.debug("now {}" , "用户菜单为空！");
			return new EmptyResponse("菜单数据");
		}
	}
	
	@RequestMapping("saveRoleMenuPermission")
	@ResponseBody
	public Response saveRoleMenuPermission(HttpServletRequest request, HttpServletResponse response){
		try{
			String menuId = request.getParameter("menuId");
			String permissionIds = request.getParameter("permissionIds");
			String roleId = request.getParameter("roleId");
			String[] permissionIdArray = permissionIds.split(",");
			menuPermissionService.deleteMenuPermissionByParams(menuId, roleId);
			for(int i=0;i<permissionIdArray.length;i++){
				MenuPermission menuPermission = new MenuPermission();
				menuPermission.setMenu_id(menuId);
				menuPermission.setRole_id(roleId);
				menuPermission.setPermission_id(permissionIdArray[i]);
				menuPermission.setStatus(EnumStatus.AVAILABLE);
				menuPermission.setCreate_time(new Date());
				menuPermissionService.saveMenuPermission(menuPermission);
			}
			return new NormalResponse();
		}catch (Exception e) {
			logger.error("分配角色-菜单-权限关系出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("showPermissionByParams")
	@ResponseBody
	public Response showPermissionByMenuIdAndRoleIdAndPermissId(HttpServletRequest request, HttpServletResponse response){
		try{
			String menuId = request.getParameter("menuId");
			String roleId = request.getParameter("roleId");
			MenuPermission menuPermission = new MenuPermission();
			menuPermission.setMenuPermission_id(null);
			menuPermission.setMenu_id(menuId);
			menuPermission.setRole_id(roleId);
			List<MenuPermission> menuPermissions= menuPermissionService.findMenuPermission(menuPermission);
			List<Permission> permissions = new ArrayList<Permission>();
			for(MenuPermission mp:menuPermissions){
				Permission pm = permissionService.getPermissionByPermissionId(mp.getPermission_id());
				permissions.add(pm);
			}
			return new NormalResponse(permissions);
		}catch (Exception e) {
			logger.error("查询已选择权限异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
}
